package cc.yaomm.common.basic.captcha;

import cc.yaomm.common.basic.captcha.generator.CaptchaGenerator;
import cc.yaomm.common.basic.captcha.handler.CaptchaHandler;
import cc.yaomm.common.basic.enums.CaptchaType;
import cc.yaomm.common.basic.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * Created by XQL on 2020/5/14.
 * 验证码业务逻辑类
 */
public class CaptchaBusiness {

    @Autowired
    CaptchaGenerator captchaGenerator;

    @Autowired
    Map<CaptchaType, CaptchaHandler> captchaHandlerMap;

    /**
     * <p>@Description : 生成验证码</p>
     * <p>@Author : QiLin.Xing </p>
     * <p>@Date : 2020/5/15  </p>
     */
    public String generate(CaptchaType captchaType, String payload, Object... params) {
        return this.getCaptchaHandler(captchaType).generate(captchaType, payload, params);
    }

    /**
     * <p>@Description : 验证验证码</p>
     * <p>@Author : QiLin.Xing </p>
     * <p>@Date : 2020/5/20  </p>
     */
    public boolean verify(CaptchaType captchaType, String payload, String code) {
        return this.getCaptchaHandler(captchaType).verify(captchaType, payload, code);
    }

    private CaptchaHandler getCaptchaHandler(CaptchaType captchaType) {
        //根据业务种类实例服务
        CaptchaHandler captchaHandler = captchaHandlerMap.get(captchaType);
        if (captchaHandler == null) {
            throw new BusinessException("不支持此种方式的验证码，请配置相关参数支持");
        }
        return captchaHandler;
    }
}
